package com.allwees.bs.task.order.notify;

import cn.hutool.core.collection.CollectionUtil;
import com.allwees.bs.core.model.order.config.ScheduleTimeProperties;
import com.allwees.bs.module.mms.dao.RetailerDao;
import com.allwees.bs.module.mms.entity.Retailer;
import com.allwees.bs.module.oms.dao.OmsOrderItemDao;
import com.allwees.bs.module.oms.dao.OrderItemDao;
import com.allwees.bs.module.oms.entity.OmsOrderItem;
import com.allwees.core.common.constant.EStatus;
import com.allwees.sender.sms.SmsSender;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service

public class OrderUnShippedNotifyTask {

    @Autowired
    private ScheduleTimeProperties scheduleTimeProperties;

    @Autowired
    private OmsOrderItemDao omsOrderItemDao;

    @Autowired
    private OrderItemDao orderItemDao;

    @Autowired
    private SmsSender smsSender;

    @Autowired
    private RetailerDao retailerDao;

    @XxlJob(value = "orderUnShippedNotifyTask")
    public ReturnT<String> run(String s) {
        doTask();
        return ReturnT.SUCCESS;
    }
    private void doTask() {
        Integer overTimeUnShipped = scheduleTimeProperties.getUnShippedNotifySecond();
        if (null == overTimeUnShipped) {
            return;
        }
        log.info("===========[orderUnShippedNotifyTask start]===========");
        List<OmsOrderItem> omsOrderItems = omsOrderItemDao.findUnShippedUuids(EStatus.OMS_WAIT_MERCHANT_SHIP.value(),overTimeUnShipped);
        if(CollectionUtil.isEmpty(omsOrderItems)){
            log.info("===========[orderUnShippedNotifyTask end, oms_un_shipped order not find]===========");
            return;
        }
        log.info(">>> un_shipped order items,size={}",omsOrderItems.size());
        Map<String, List<OmsOrderItem>> map = omsOrderItems.stream().collect(Collectors.groupingBy(OmsOrderItem::getRetailerUuid,Collectors.toList()));
        for(Map.Entry<String, List<OmsOrderItem>> entry:map.entrySet()){
            List<OmsOrderItem> list = entry.getValue();
            Retailer retailer = retailerDao.findByUuid(entry.getKey());
            String mobile = retailer.getPhone();
            if (StringUtils.isBlank(mobile)) {
                log.info("Retailer [{}] phone is null,Retailer uuid:{}", retailer.getCompanyName(),retailer.getUuid());
                continue;
            }
            smsSender.merchantUnShippedNotifySendSms(mobile,list.size(),overTimeUnShipped/3600);
        }
    }
}
